from django.http import JsonResponse
from django.core.exceptions import ObjectDoesNotExist, ValidationError
import logging

logger = logging.getLogger(__name__)

class GlobalExceptionHandlerMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        try:
            response = self.get_response(request)
        except ObjectDoesNotExist as e:
            logger.warning(f"Object not found: {str(e)}")
            response = JsonResponse({
                'code': 404,
                'message': 'Not Found',
                'remarks': 'The requested resource was not found.'
            }, status=404)
        except ValidationError as e:
            logger.warning(f"Validation error: {str(e)}")
            response = JsonResponse({
                'code': 400,
                'message': 'Bad Request',
                'remarks': 'There was a validation error.',
                'errors': e.message_dict
            }, status=400)
        except Exception as e:
            logger.error(f"Unhandled exception: {str(e)}", exc_info=True)
            response = JsonResponse({
                'code': 500,
                'message': 'Internal Server Error',
                'remarks': 'An unexpected error occurred.'
            }, status=500)
        return response